package com.bacon.gmall.user.comtroller;

import com.bacon.gmall.common.constant.RedisConst;
import com.bacon.gmall.common.result.Result;
import com.bacon.gmall.model.user.UserInfo;
import com.bacon.gmall.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author： bacon、
 * @version： 1.0
 * @create： 2021-01-03 19:24
 * @description:
 */
@RestController
@RequestMapping("/api/user/passport")
public class LoginApiController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    //异步提交对象需要使用@RequestBody
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo) {
        
        //判断用户名是否为空？
        if (null == userInfo) {
            return Result.fail().message("提交对象为空");
        }
        if (StringUtils.isEmpty(userInfo.getLoginName())) {
            return Result.fail().message("提交用户名为空");
        }

        //判断密码是否为空？
        if (StringUtils.isEmpty(userInfo.getPasswd())) {
            return Result.fail().message("提交密码为空");
        }

        //校验DB
        UserInfo userInfo1 = loginService.login(userInfo);
        if (null == userInfo1) {
            return Result.fail().message("用户名或者密码错误");
        }
        Map map = new HashMap<>();
        //传递token
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        map.put("token", uuid);
        //昵称
        map.put("nickName",userInfo1.getNickName());
        //保存Redis一份
        redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + uuid,userInfo1.getId().toString(),30, TimeUnit.DAYS);
        return Result.ok(map);
    }
}
